<template>
  <div class="users">
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- .native修饰符的作用是，让封装的组件也能够绑定原生的事件 -->
    <el-input placeholder="请输入内容" v-model="searchVal" class="search-input" @keydown.enter.native="searchUser">
      <el-button slot="append" icon="el-icon-search" @click="searchUser"></el-button>
    </el-input>

    <el-button type="primary" plain @click="addDialogFormVisible = true">添加用户</el-button>

    <!-- 表格 -->
    <el-table
      class="mt-15"
      :data="userList"
      border
      style="width: 100%">
      <el-table-column
        type="index"
        width="50">
      </el-table-column>
      <el-table-column
        prop="username"
        label="姓名">
      </el-table-column>
      <el-table-column
        prop="email"
        label="邮箱">
      </el-table-column>
      <el-table-column
        prop="mobile"
        label="电话">
      </el-table-column>
      <el-table-column
        prop=""
        label="状态">
        <template slot-scope="scope">
          <!-- 7.1 此处的v-model应该是scope.row.mg_state -->
          <!-- 7.2 监听开关的change事件，并将当前要改变状态的那一行数据作为参数传入函数中 -->
          <el-switch
            @change="toggleState(scope.row)"
            v-model="scope.row.mg_state"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        prop=""
        label="操作">
        <!-- 通过scope.row可以取到表格那一行对象里面的属性 -->
        <template slot-scope="scope">
          <!-- 点击编辑将当前点击用户的所有信息传递到函数中去 -->
          <el-button type="primary" icon="el-icon-edit" circle @click="handleEditUser(scope.row)"></el-button>
          <!-- scope.row.id可以将你点击的那个用户的id取到，传递给函数发请求 -->
          <el-button type="danger" icon="el-icon-delete" circle @click="handleDelUser(scope.row.id)"></el-button>
          <el-button type="warning" icon="el-icon-check" circle @click="handleGrantUser(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      class="page mt-15"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="1"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalNum">
    </el-pagination>

    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogFormVisible">
      <el-form :model="addForm" ref="addFormRef" :rules="myrules">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAdd('addFormRef')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogFormVisible">
      <el-form :model="editForm" ref="editFormRef" :rules="myrules">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEdit('editFormRef')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 8.1 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="grantDialogFormVisible">
      <el-form :model="grantForm" ref="grantFormRef" :rules="myrules">
        <el-form-item label="当前用户" :label-width="formLabelWidth">
          <el-input v-model="grantForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="选择角色" :label-width="formLabelWidth">
          <!-- 8.3 完成选择器使用，注意label字段表示的是显示的文字，value表示文字所对应的值，最终用户选了一个选项之后，会将将那个选项的value值传给el-select组件中的v-model的变量 -->
          <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="grantDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitGrant">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {getUserList, addUser, delUser, editUser, changeState, getRoles, grantRole} from '@/api'
export default {
  data () {
    // 定义自定义校验规则所需的函数
    let checkEmail = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入邮箱'))
      } else {
        // 校验邮箱规则
        // eslint-disable-next-line
        let emailReg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/
        if (emailReg.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的邮箱格式'))
        }
      }
    }
    return {
      searchVal: '',
      userList: [],
      totalNum: 0, // 用户总条数
      pagesize: 10, // 每页显示多少条，默认为3条
      pagenum: 1, // 当前页码，默认为第一页

      addDialogFormVisible: false, // 添加用户对话框的显示于隐藏
      formLabelWidth: '80px', // 设置input左侧文字的宽度
      // 添加用户表单的字段
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },

      editDialogFormVisible: false,
      editForm: {
        id: -1,
        username: '',
        email: '',
        mobile: ''
      },

      // 8.2 分配角色对话框中所需字段
      grantForm: {
        username: '',
        id: '' // 用户id
      },
      grantDialogFormVisible: false,
      selectRoleId: '', // 选中之后的角色id
      roleList: [], // 8.5 角色列表

      myrules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        email: [
          // 自定义校验邮箱规则
          { required: true, validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' }
        ]
      },

      state: ''
    }
  },
  created () {
    // 调用初始化table的方法
    this.initTable()
  },
  methods: {
    // 初始化table数据的方法
    initTable () {
      getUserList({query: this.searchVal, pagenum: this.pagenum, pagesize: this.pagesize})
        .then(res => {
          console.log(res)
          // 1.1 给用户总条数赋值
          this.totalNum = res.data.total
          this.userList = res.data.users
        })
    },
    // 搜索用户
    searchUser () {
      this.initTable()
      this.searchVal = ''
    },
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      // 1.3 改变每页多少条的时候，将这个值赋值给pagesize属性，接着再调用获取数据的方法
      this.pagesize = val
      this.initTable()
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      // 1.4 改变当前页码时，将当前页面的值赋值给pagenum属性，接着再调用获取数据的方法
      this.pagenum = val
      this.initTable()
    },
    // 提交添加用户
    submitAdd (formRef) {
      this.$refs[formRef].validate((isPass) => {
        if (isPass) {
          addUser(this.addForm)
            .then(res => {
              if (res.meta.status === 201) {
                this.$message.success('添加用户成功')
                this.addDialogFormVisible = false
                // 清空表单
                this.addForm.username = ''
                this.addForm.password = ''
                this.addForm.email = ''
                this.addForm.mobile = ''
                // 刷新表格数据
                this.initTable()
              }
            })
        } else {
          this.$message.warning('请正确填写表单')
        }
      })
    },
    // 删除用户
    handleDelUser (id) {
      // 让提示框显示
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 点击确定执行的回调函数
        delUser(id)
          .then(res => {
            if (res.meta.status === 200) {
              this.initTable()
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            } else {
              this.$message.error(res.meta.msg)
            }
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 编辑用户
    handleEditUser (row) {
      // 6.1 让编辑对话框显示，并且给编辑对话框里面的form表单赋一个默认值
      this.editForm.id = row.id
      this.editForm.username = row.username
      this.editForm.email = row.email
      this.editForm.mobile = row.mobile
      this.editDialogFormVisible = true
    },
    // 提交编辑
    submitEdit (formRef) {
      // 6.2 先js校验，校验通过就发送编辑用户的请求
      this.$refs[formRef].validate((isPass) => {
        if (isPass) {
          editUser(this.editForm)
            .then(res => {
              if (res.meta.status === 200) {
                this.$message.success(res.meta.msg)
                this.editDialogFormVisible = false
                this.initTable()
              }
            })
        } else {
          this.$message.warning('请正确填写表单')
        }
      })
    },
    // 切换状态
    toggleState (row) {
      // 7.3 直接将传入进来的这个对象的id， 以及更改后的状态传入接口函数中
      changeState(row.id, row.mg_state)
        .then(res => {
          this.$message.success(res.meta.msg)
        })
    },
    // 显示分类角色对话框
    handleGrantUser (row) {
      this.grantForm.username = row.username
      this.grantForm.id = row.id // 给用户id赋值
      this.grantDialogFormVisible = true
      this.selectRoleId = row.role_name // 此处为了解决点击显示分配角色弹框时，每个用户默认角色一样的bug
      // 8.4 调用接口获取角色列表
      getRoles()
        .then(res => {
          // 8.5 在data中定义变量，将获取的角色列表保存起来
          console.log(res)
          this.roleList = res.data
        })
    },
    // 提交分配角色
    submitGrant () {
      // 8.7 发请求之前，先判断selectRoleId是否为字符串，如果为字符串说明用户没有更改角色，直接return就行了
      if (typeof this.selectRoleId === 'string') {
        this.grantDialogFormVisible = false
        return false
      }
      // 8.6 发请求分配角色
      grantRole(this.grantForm.id, this.selectRoleId)
        .then(res => {
          this.$message.success(res.meta.msg)
          // 必须刷新表格
          this.initTable()
          this.grantDialogFormVisible = false
        })
    }
  }
}
</script>
<style lang="scss" scoped>
.search-input {
  width: 300px;
}
</style>
